"""自定义异常类

定义区块链中间件系统中使用的各种异常类型
"""

class BlockchainMiddlewareException(Exception):
    """区块链中间件基础异常类"""
    
    def __init__(self, message: str, error_code: str = None, details: dict = None):
        super().__init__(message)
        self.message = message
        self.error_code = error_code or 'UNKNOWN_ERROR'
        self.details = details or {}
    
    def to_dict(self) -> dict:
        """转换为字典格式"""
        return {
            'error_type': self.__class__.__name__,
            'error_code': self.error_code,
            'message': self.message,
            'details': self.details
        }

# API网关相关异常
class APIGatewayException(BlockchainMiddlewareException):
    """API网关异常"""
    pass

class AuthenticationException(APIGatewayException):
    """认证异常"""
    
    def __init__(self, message: str = "Authentication failed", error_code: str = 'AUTH_FAILED'):
        super().__init__(message, error_code)

class AuthorizationException(APIGatewayException):
    """授权异常"""
    
    def __init__(self, message: str = "Authorization failed"):
        super().__init__(message, 'AUTH_DENIED')

class RateLimitException(APIGatewayException):
    """速率限制异常"""
    
    def __init__(self, message: str = "Rate limit exceeded"):
        super().__init__(message, 'RATE_LIMIT_EXCEEDED')

class RequestValidationException(APIGatewayException):
    """请求验证异常"""
    
    def __init__(self, message: str = "Request validation failed", validation_errors: list = None):
        super().__init__(message, 'VALIDATION_FAILED', {'validation_errors': validation_errors or []})

# 统一抽象层相关异常
class UnifiedAbstractionException(BlockchainMiddlewareException):
    """统一抽象层异常"""
    pass

class AdapterException(UnifiedAbstractionException):
    """适配器异常"""
    
    def __init__(self, message: str, chain_id: str = None):
        super().__init__(message, 'ADAPTER_ERROR', {'chain_id': chain_id})

class ChainNotSupportedException(UnifiedAbstractionException):
    """不支持的区块链类型异常"""
    
    def __init__(self, message: str, chain_type: str = None):
        super().__init__(message, 'CHAIN_NOT_SUPPORTED', {'chain_type': chain_type})

class OperationNotSupportedException(UnifiedAbstractionException):
    """不支持的操作异常"""
    
    def __init__(self, message: str, operation: str = None, chain_type: str = None):
        super().__init__(message, 'OPERATION_NOT_SUPPORTED', {
            'operation': operation,
            'chain_type': chain_type
        })

class ChainException(UnifiedAbstractionException):
    """区块链操作异常"""
    
    def __init__(self, message: str, chain_id: str = None, operation: str = None):
        super().__init__(message, 'CHAIN_ERROR', {
            'chain_id': chain_id,
            'operation': operation
        })

class TransactionException(ChainException):
    """交易异常"""
    
    def __init__(self, message: str, tx_hash: str = None, chain_id: str = None):
        super().__init__(message, chain_id, 'transaction')
        self.details['tx_hash'] = tx_hash
        self.error_code = 'TRANSACTION_ERROR'

class ContractException(ChainException):
    """智能合约异常"""
    
    def __init__(self, message: str, contract_address: str = None, chain_id: str = None):
        super().__init__(message, chain_id, 'contract')
        self.details['contract_address'] = contract_address
        self.error_code = 'CONTRACT_ERROR'

class ContractNotFoundException(ContractException):
    """合约未找到异常"""
    
    def __init__(self, message: str = "Contract not found", contract_address: str = None, chain_id: str = None):
        super().__init__(message, contract_address, chain_id)
        self.error_code = 'CONTRACT_NOT_FOUND'

class AccountException(ChainException):
    """账户异常"""
    
    def __init__(self, message: str, account_address: str = None, chain_id: str = None):
        super().__init__(message, chain_id, 'account')
        self.details['account_address'] = account_address
        self.error_code = 'ACCOUNT_ERROR'

# 智能合约管理相关异常
class SCMException(BlockchainMiddlewareException):
    """智能合约管理异常"""
    pass

class ContractDeploymentException(SCMException):
    """合约部署异常"""
    
    def __init__(self, message: str, contract_name: str = None):
        super().__init__(message, 'CONTRACT_DEPLOYMENT_FAILED', {'contract_name': contract_name})

class ContractTemplateException(SCMException):
    """合约模板异常"""
    
    def __init__(self, message: str, template_id: str = None):
        super().__init__(message, 'CONTRACT_TEMPLATE_ERROR', {'template_id': template_id})

# 智能合约版本管理相关异常
class SCVMException(BlockchainMiddlewareException):
    """智能合约版本管理异常"""
    pass

class VersionException(SCVMException):
    """版本异常"""
    
    def __init__(self, message: str, version: str = None, contract_id: str = None):
        super().__init__(message, 'VERSION_ERROR', {
            'version': version,
            'contract_id': contract_id
        })

class VersionNotFoundException(VersionException):
    """版本未找到异常"""
    
    def __init__(self, message: str = "Version not found", version: str = None, contract_id: str = None):
        super().__init__(message, version, contract_id)
        self.error_code = 'VERSION_NOT_FOUND'

class VersionConflictException(VersionException):
    """版本冲突异常"""
    
    def __init__(self, message: str = "Version conflict", version: str = None, contract_id: str = None):
        super().__init__(message, version, contract_id)
        self.error_code = 'VERSION_CONFLICT'

class UpgradeException(SCVMException):
    """升级异常"""
    
    def __init__(self, message: str, upgrade_plan_id: str = None):
        super().__init__(message, 'UPGRADE_FAILED', {'upgrade_plan_id': upgrade_plan_id})

class RollbackException(SCVMException):
    """回滚异常"""
    
    def __init__(self, message: str, rollback_plan_id: str = None):
        super().__init__(message, 'ROLLBACK_FAILED', {'rollback_plan_id': rollback_plan_id})

# 区块链监控网络相关异常
class MonitoringException(BlockchainMiddlewareException):
    """监控异常"""
    pass

class AlertException(MonitoringException):
    """告警异常"""
    
    def __init__(self, message: str, alert_id: str = None):
        super().__init__(message, 'ALERT_ERROR', {'alert_id': alert_id})

class MetricsException(MonitoringException):
    """指标异常"""
    
    def __init__(self, message: str, metric_type: str = None):
        super().__init__(message, 'METRICS_ERROR', {'metric_type': metric_type})

# 监管审计网关相关异常
class AuditException(BlockchainMiddlewareException):
    """审计异常"""
    pass

class ComplianceException(AuditException):
    """合规异常"""
    
    def __init__(self, message: str, rule_id: str = None, violation_type: str = None):
        super().__init__(message, 'COMPLIANCE_VIOLATION', {
            'rule_id': rule_id,
            'violation_type': violation_type
        })

class PrivacyException(AuditException):
    """隐私异常"""
    
    def __init__(self, message: str, data_type: str = None):
        super().__init__(message, 'PRIVACY_VIOLATION', {'data_type': data_type})

# 数据验证相关异常
class ValidationException(BlockchainMiddlewareException):
    """数据验证异常"""
    
    def __init__(self, message: str, field: str = None, value=None):
        super().__init__(message, 'VALIDATION_ERROR', {
            'field': field,
            'value': str(value) if value is not None else None
        })

class SchemaValidationException(ValidationException):
    """模式验证异常"""
    
    def __init__(self, message: str, schema_errors: list = None):
        super().__init__(message, 'schema', None)
        self.error_code = 'SCHEMA_VALIDATION_ERROR'
        self.details['schema_errors'] = schema_errors or []

# 配置相关异常
class ConfigurationException(BlockchainMiddlewareException):
    """配置异常"""
    
    def __init__(self, message: str, config_key: str = None):
        super().__init__(message, 'CONFIG_ERROR', {'config_key': config_key})

# 数据库相关异常
class DatabaseException(BlockchainMiddlewareException):
    """数据库异常"""
    
    def __init__(self, message: str, operation: str = None, collection: str = None):
        super().__init__(message, 'DATABASE_ERROR', {
            'operation': operation,
            'collection': collection
        })

class ConnectionException(DatabaseException):
    """连接异常"""
    
    def __init__(self, message: str = "Database connection failed"):
        super().__init__(message, 'connection', None)
        self.error_code = 'CONNECTION_ERROR'

# 网络相关异常
class NetworkException(BlockchainMiddlewareException):
    """网络异常"""
    
    def __init__(self, message: str, endpoint: str = None, status_code: int = None):
        super().__init__(message, 'NETWORK_ERROR', {
            'endpoint': endpoint,
            'status_code': status_code
        })

class TimeoutException(NetworkException):
    """超时异常"""
    
    def __init__(self, message: str = "Request timeout", timeout_seconds: int = None):
        super().__init__(message, None, None)
        self.error_code = 'TIMEOUT_ERROR'
        self.details['timeout_seconds'] = timeout_seconds

# 加密相关异常
class CryptographyException(BlockchainMiddlewareException):
    """加密异常"""
    
    def __init__(self, message: str, operation: str = None):
        super().__init__(message, 'CRYPTO_ERROR', {'operation': operation})

class SignatureException(CryptographyException):
    """签名异常"""
    
    def __init__(self, message: str = "Signature verification failed"):
        super().__init__(message, 'signature')
        self.error_code = 'SIGNATURE_ERROR'

class EncryptionException(CryptographyException):
    """加密异常"""
    
    def __init__(self, message: str = "Encryption/Decryption failed"):
        super().__init__(message, 'encryption')
        self.error_code = 'ENCRYPTION_ERROR'

# 业务逻辑相关异常
class BusinessLogicException(BlockchainMiddlewareException):
    """业务逻辑异常"""
    pass

class InsufficientBalanceException(BusinessLogicException):
    """余额不足异常"""
    
    def __init__(self, message: str = "Insufficient balance", required_amount: float = None, available_amount: float = None):
        super().__init__(message, 'INSUFFICIENT_BALANCE', {
            'required_amount': required_amount,
            'available_amount': available_amount
        })

class DuplicateOperationException(BusinessLogicException):
    """重复操作异常"""
    
    def __init__(self, message: str = "Duplicate operation detected", operation_id: str = None):
        super().__init__(message, 'DUPLICATE_OPERATION', {'operation_id': operation_id})

class ResourceNotFoundException(BusinessLogicException):
    """资源未找到异常"""
    
    def __init__(self, message: str = "Resource not found", resource_type: str = None, resource_id: str = None):
        super().__init__(message, 'RESOURCE_NOT_FOUND', {
            'resource_type': resource_type,
            'resource_id': resource_id
        })

class ResourceConflictException(BusinessLogicException):
    """资源冲突异常"""
    
    def __init__(self, message: str = "Resource conflict", resource_type: str = None, resource_id: str = None):
        super().__init__(message, 'RESOURCE_CONFLICT', {
            'resource_type': resource_type,
            'resource_id': resource_id
        })

# 异常处理工具函数
def handle_exception(exception: Exception) -> dict:
    """处理异常并返回标准化的错误响应"""
    if isinstance(exception, BlockchainMiddlewareException):
        return {
            'success': False,
            'error': exception.to_dict()
        }
    else:
        # 处理未知异常
        return {
            'success': False,
            'error': {
                'error_type': 'UnknownException',
                'error_code': 'UNKNOWN_ERROR',
                'message': str(exception),
                'details': {}
            }
        }

def create_error_response(error_code: str, message: str, details: dict = None, status_code: int = 400) -> tuple:
    """创建标准化的错误响应"""
    error_response = {
        'success': False,
        'error': {
            'error_code': error_code,
            'message': message,
            'details': details or {}
        }
    }
    return error_response, status_code